#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LISTEN_SZ 10
/*
运行服务端程序， 然后再运行客户端程序， 服务端会接受到客户端连接的ip和端口
*/
int main(int argc, char const *argv[])
{
    struct sockaddr_in svr_addr,client_addr;
    // 创建套接字
    int sock_fd = socket(AF_INET,SOCK_STREAM,0);
    if(sock_fd == -1)
    {
        perror("socket");
        exit(1);
    }
    printf("socket fd = %d\n", sock_fd);
    bzero(&svr_addr, sizeof(struct sockaddr_in));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_port = htons(atoi(argv[2]));
    svr_addr.sin_addr.s_addr = inet_addr(argv[1]);

    // 1.bind
    int ret = bind(sock_fd,(struct sockaddr *)&svr_addr,sizeof(struct sockaddr_in));
    if (ret == -1) {
        perror("bind error");
        close(sock_fd);
        exit(1);
    }
    // 2. listen accpet
    ret = listen(sock_fd, LISTEN_SZ);

    if (ret == -1) {
        perror("listen error");
        exit(1);
        close(sock_fd);
    }
    

    bzero(&client_addr, sizeof(client_addr));

    socklen_t len = sizeof(struct sockaddr);
    int cfd = accept(sock_fd,(struct sockaddr *)&client_addr,&len);
    if (cfd == -1) {
        perror("accept error");
        exit(EXIT_FAILURE);
    }

    printf("ip :%s , port: %d \n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    close(sock_fd);
    close(cfd);

    return 0;
}
